package com.dushuren.project.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.TeamCureExamineMapper;
import com.dushuren.project.model.entity.TeamCureExamine;
import com.dushuren.project.service.TeamCureExamineService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/***
 * 定时删除 teamCureApply表中的 通过 | 拒绝 数据
 */
@Component
@Slf4j
public class delTeamCureApplyJob {

  @Resource
  private TeamCureExamineService teamCureExamineService;

  @Resource
  private TeamCureExamineMapper teamCureExamineMapper;

  @Resource
  RedissonClient redissonClient;
  /***
   * 每天 0  12 点自动执行
   * 但消息超过 20 条时进行删除
   */
  @Scheduled(cron = "0 0 12,0 * * ?")
  public void doStart() {

    RLock lock = redissonClient.getLock("dushuren:delete:start:lock");

    try {
      if (lock.tryLock(0, -1, TimeUnit.MICROSECONDS)) {
        log.info("delTeamCureApplyJob start");
        QueryWrapper<TeamCureExamine>  queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.notIn("examineState", 0);
        Long count = teamCureExamineMapper.selectCount(queryWrapper);
        if (count > 20 ) {
          teamCureExamineService.remove(queryWrapper);
        }
      }
    } catch (InterruptedException e) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, " 删除失败");
    } finally {
      if (lock.isHeldByCurrentThread()) {
        lock.unlock();
        log.info("delTeamCureApplyJob end");
      }
    }
  }

}
